/*
 * @Author: gk 
 *  表建模型
 * @Date: 2018-03-15 14:44:57 
 * @Last Modified by: csy
 * @Last Modified time: 2019-09-23 14:45:22
 */
layui.config({
}).use(['element', 'zlConfig', 'zlContext', 'zlSelectEx','zltreemenu', 'zlSelectMultiple', 'table', 'layer', 'form', 'zlPinYin','laydate'], function (exports) {
	var $ = layui.$
		, zlContext = layui.zlContext
		, zltreemenu = layui.zltreemenu
		, layer = layui.layer
        , table = layui.table
        , element = layui.element
		, form = layui.form
		, zlPinYin = layui.zlPinYin
		, zlConfig = layui.zlConfig
		, statusName = zlConfig.global.result.statusName
		, msgName = zlConfig.global.result.msgName
		, dataName = zlConfig.global.result.dataName
		, OK = zlConfig.global.result.okState
		, fullheight = 'full-370'
        , exportData = {}
        , loadingLayer
        , intervalId = undefined;
    
        // layui.use('laydate', function(exports){
        //     element.render();
        // });

	form.verify({
		tableName: function (value, item) {
			if (!new RegExp("^[a-zA-Z][a-zA-Z0-9_]{0,30}$").test(value)) {
				return '表模型编号只能使用[字母开头的最大长度不超过30的字符串]';
			}
		},
		columnName: function (value, item) {
			if (!new RegExp("^[a-zA-Z][a-zA-Z0-9_]{0,30}$").test(value)) {
				return '模型列编号只能使用[字母开头的最大长度不超过30的字符串]';
			}
		},
		commentVerify: function (value, item) {
			if (!new RegExp("^[\u4E00-\u9FA5A-Za-z0-9_:]+$").test(value)) {
				return '名称不能有特殊字符';
			}
		}

	});
	var treeObj;
	var fromlayerIndex;
	var newAddTableId;
	var treeAction = {
		loadTree: function () {
			//创建zTree组件
			treeObj = zltreemenu.render('orgTreeId',{
				dataurl: $('#orgTreeId').attr('url'),
				type: 'get',
				name: 'MX_MINGC',
				tableId: 'tbField|tbIndex',
				isMove: true
			},{
				onClick: function (event, treeId, treeNode) {
					//触发刷新的事件
					treeAction.raiseResDataEvent(treeNode);
				},
				onRightClick: function (event, treeId, treeNode) {
					// 显示右键菜单
					if (event.target.tagName.toLowerCase() == 'a' || event.target.tagName.toLowerCase() == 'span') {
                        treeObj.selectNode(treeNode);
                        treeAction.raiseResDataEvent(treeNode);
						var event = event || window.event;
						$('#rightButtonMenu').removeClass('layui-hide').addClass('layui-show').css({
							'top': event.clientY - event.offsetY + $(event.target).height() + 'px',
							'left': event.clientX
						}).attr('tid', $(event.target).parents('li').prop('id'));
					}
				},
				onAsyncSuccess: function (event, treeId, treeNode, msg) {
					if(newAddTableId){
						var newNode = treeObj.getNodeByParam('RWID',newAddTableId,null);
						if(newNode){
							treeObj.selectNode(newNode);
							treeAction.raiseResDataEvent(newNode);
							newAddTableId = undefined;
						}else{
							treeObj.selectNode(treeObj.getNodes()[0]);
							treeAction.raiseResDataEvent(treeObj.getNodes()[0]);
						}
					}else{
						treeObj.selectNode(treeObj.getNodes()[0]);
						treeAction.raiseResDataEvent(treeObj.getNodes()[0]);
					}
				},
                beforeDrag: function (treeID, treeNodes) {
                    for (var i = 0; i < treeNodes.length; i++) {
                        if (treeNodes[i].RWID == '2FEF611CE3A140D7B9C8235BB1C14D22') {
                            zlContext.errorMsg('表模型节点不能移动');
                            return false;
                        }
                    }
                },
                beforeDrop: function (treeId, treeNodes, targetNode, moveType) {
                    if (targetNode == null) {
                        zlContext.errorMsg('表只能拖拽到表模型节点之下！');
                        return false;
                    }
                },
                beforeDragOpen: function (treeId, treeNode) {
                    return false;
                },
                onDrop: function (event, treeId, treeNodes, targetNode, moveType) {
                    // 选择一个根节点
                    if (moveType == null) {
                        return;
                    }
                    if (targetNode == null) {
                        zlContext.errorMsg('表只能拖拽到表模型节点之下！');
                        return;
                    }
                    if (moveType == 'prev' || moveType == 'next') {
                        var nodes = treeObj.getSelectedNodes();
                        /*根据 zTree 的唯一标识 tId 快速获取节点 JSON 数据对象*/
                        var targetNode = treeObj.getNodeByTId(nodes[0].parentTId);
                        if (targetNode == null) {
                            zlContext.errorMsg("表只能拖拽到表模型节点之下！");
                            return;
                        }
                    }
                    var sourcestreenode = treeNodes[0],
                        parentNodeRwid = targetNode.RWID,
                        parentsid = sourcestreenode.SYS_PARENTS,
                        isleaf = 0,
                        data = {};               
                        parentsid = targetNode.SYS_PARENTS + "_" + parentsid.substr(parentsid.indexOf(sourcestreenode.RWID), parentsid.length);           
                    data = {
                        RWID: sourcestreenode.RWID,
                        SYS_PARENTID: parentNodeRwid,
                        SYS_PARENTS: parentsid,
                    };
                    zlContext.post(layui.cache['contentPath'] + '/manager/coretables/drag', data, function (result) {
                        if (result[statusName] == OK) {
                            treeAction.raiseResDataEvent();;
                        } else {
                            zlContext.errorMsg(result[msgName]);               
                        }
                    })
                }
			})
		},
		treeFormEdit: function (node, type, readonly) {
			var readonly = readonly && readonly != 0 ? 'disabled' : '';
			var frm = [
				'<div class="site-block"> <form id ="frmTreeForm" class="layui-form" action="">'
				, '	<div class="layui-form-item layui-hide">'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="EDITTYPE" class="layui-input">'
				, '			<input type="text" name="MX_SHIFCJ" class="layui-input">'
				, '			<input type="text" name="RWID" class="layui-input">'
				, '			<input type="text" name="SYS_PARENTID" class="layui-input">'
				, '			<input type="text" name="SYS_PARENTS" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">名称</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="MX_MINGC" maxlength="30" ' + readonly + ' lay-verify="required|commentVerify" placeholder="请输入名称"  class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">编号</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="MX_BIANH" ' + readonly + ' lay-verify="required|tableName" placeholder="请输入编号"  class="layui-input" maxlength="30">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">主键字段</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="MX_ZHUJZD" disabled lay-verify="required" placeholder="请输主键字段"  class="layui-input" maxlength="50"> '
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">表类型</label>'
				, '		<div class="layui-input-block">'
				, '		  <select name="MX_BIAOLX" ' + readonly + ' lay-verify="required"  placeholder="请选择表类型" zlcomponent class="select-ext" settings="{titlefield: \'VALUE\', valuefield: \'CODE\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coredictionary/querydictionarybyid?RWID=1589F6CBD7F94D5A85D206D18B1F41BE' + '\'}">'
				, '		  </select>'
				, '		</div>'
				, '	</div>  '
				, '	<div class="layui-form-item">'
				, '		<div class="layui-input-block">'
				, '		  <button class="layui-btn" lay-submit lay-filter="frmTreeForm"  ' + readonly + '>保存</button>'
				, '		</div>'
				, '	</div>'
				, '</form></div>'
			];
			layer.open({
				type: 1,
				title: type == 'edit' ? '编辑' : '新增',
				id: 'coreTableTreeLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
					if (type == 'edit') {
						if(!node["MX_ZHUJZD"]){
							node["MX_ZHUJZD"] = "RWID";
						}
						zlContext.autoFill($('#frmTreeForm'), node);
						$('#frmTreeForm input[name=EDITTYPE]').val('edit');
					}
					else {
						/**设置隐藏属性 */
						$('#frmTreeForm input[name=EDITTYPE]').val('new');
						$('#frmTreeForm input[name=MX_SHIFCJ]').val('0');
						$('#frmTreeForm input[name=MX_ZHUJZD]').val('RWID');
						$('#frmTreeForm input[name=SYS_PARENTID]').val(node['RWID']);
					}
					$('#frmTreeForm input[name=MX_MINGC]').change(function () {
						var v = $('#frmTreeForm input[name=MX_MINGC]').val();
						var h = node['MX_BIANH'] == 'TABLEMODEL' ? '' : $('#frmTable input[name=MX_BIANH]').val() + '_';
						/**模型名 */
						var v1 = h + zlPinYin.C(v);
						$('#frmTreeForm input[name=MX_BIANH]').val(v1);
						/**主键名 */
						var pid = 'RWID';//v1 + '_ID'
						$('#frmTreeForm input[name=MX_ZHUJZD]').val(pid);
					});
					fromlayerIndex = index;
					form.render();
				},
				cancel: function (index, layero) {
					if (type == 'edit') {
						treeAction.newFields = null;
						if ($('#frmTreeForm').find('.getField').length == 0) {
							$('#frmTreeForm').append('<button class="layui-btn layui-hide getField" lay-submit lay-filter="frmTreeForm">获取表单值</button>');
						}
						var verifyItem = $('#frmTreeForm').find('[lay-verify]');
						for (var i = 0; i < verifyItem.length; i++) {
							var verifyStr = $(verifyItem[i]).attr('lay-verify');
							if (verifyStr != '') {
								$(verifyItem[i]).attr({
									'lay-verify': '',
									'data-verifyflag': verifyStr
								})
							}
						}
						$('#frmTreeForm').find('.getField').trigger('click');
						if (treeAction.newFields == null) {
							return false;
						}
						if (!zlContext.isObjectValueEqual(treeAction.newFields, node)) {
							var changeConfirmLayer = layer.confirm('数据已有改动，是否要保存？', {
								title: '是否关闭',
								resize: false,
								btn: ['保存关闭', '确定关闭', '取消'], //按钮
								btnAlign: 'c',
								anim: 1,
								icon: 3
							}, function () {
								layer.close(changeConfirmLayer)
								var items = $('#frmTreeForm').find('[data-verifyflag]')
								for (var i = 0; i < items.length; i++) {
									var verifyStr = $(items[i]).attr('data-verifyflag');
									$(items[i]).attr({
										'lay-verify': verifyStr,
										'data-verifyflag': ''
									});
								}
								$('#frmTreeForm').find('[lay-filter="frmTreeForm"]').trigger('click');
							}, function () {
								layer.close(index)
							}, function () {
								layer.close(changeConfirmLayer)
							});
							return false;
						} else {
							layer.close(index)
						}
					}
				}
			});
		},
		/**是否能修改 跟节点是不能修改*/
		isRootNode: function () {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length > 0)
				return nodes[0]['MX_BIANH'] == 'TABLEMODEL'
			return false;
		},
		/**是否目录类型模型 */
		isCalNode: function () {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length > 0)
				return nodes[0]['MX_BIAOLX'] == 2
			return false;
		},
		addNode: function () {
			var node = treeObj.getNodeByTId($('#rightButtonMenu').attr('tid'));
			treeAction.treeFormEdit(node, 'new');
		},
		editNode: function () {
			var node = treeObj.getNodeByTId($('#rightButtonMenu').attr('tid'));
			if (node['MX_BIANH'] == 'TABLEMODEL') {
				zlContext.warnMsg('无法编辑根节点');
				return;
			}
			treeAction.treeFormEdit(node, 'edit');
		},
		deleteNode: function () {
			var node = treeObj.getNodeByTId($('#rightButtonMenu').attr('tid'));
			if (node['MX_BIANH'] == 'TABLEMODEL') {
				zlContext.warnMsg('无法删除根节点');
				return;
			}
			if (node.children && node.children.length > 0) {
				zlContext.warnMsg('无法删除包含子节点的节点');
				return;
			}
			zlContext.confirm('询问', '是否要删除选择的模型[' + node.MX_MINGC + ']?', function (index) {
				//提交删除
				zlContext.deletePost(layui.cache['contentPath'] + '/manager/coretables/remove', { id: node.RWID }, function (result) {
					if (result[statusName] == OK) {
						var nextNode = node.getPreNode() ? node.getPreNode() : node.getParentNode();
						treeObj.removeNode(node);
						if (nextNode) {
							treeObj.selectNode(nextNode);
							treeAction.raiseResDataEvent();
						}

						zlContext.successMsg('删除成功');
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		/**发起刷新明细资料的事件 */
		raiseResDataEvent: function (node) {
			var currNode = node;
			if (!node) {
				var nodes = treeObj.getSelectedNodes();
				if (nodes.length > 0)
					currNode = nodes[0];
			}
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, currNode['RWID']);
		},
		/**新增树节点显示*/
		addChildNode: function (pNode, data) {
			var treeNode = treeObj.addNodes(pNode, data);
			treeObj.selectNode(treeNode[0]);
			treeAction.raiseResDataEvent();
		},
		/**更新树的节点显示 */
		refreshNode: function (node, data) {
			$.each(data, function (k, v) {
				if (node[k]) {
					node[k] = v;
				}
			});
			treeObj.updateNode(node);
			/**刷新页面 */
			treeAction.raiseResDataEvent();
		}

	}
	//提交
	form.on('submit(frmTreeForm)', function (frm) {
		if ($(frm.elem).hasClass('getField')) {
			treeAction.newFields = frm.field
			return false;
		}
		var editType = $('#frmTreeForm input[name=EDITTYPE]').val();
		var node = treeObj.getNodeByTId($('#rightButtonMenu').attr('tid'));
		if (editType == 'new') {
			zlContext.put(layui.cache['contentPath'] + '/manager/coretables/add', frm.field, function (result) {
				if (result[statusName] == OK) {
					newAddTableId = result[dataName].RWID;
					treeAction.loadTree();
					layer.close(fromlayerIndex);
					zlContext.successMsg('保存成功');
					return true;
				}
				else {
					zlContext.errorMsg(result[msgName]);
				}
			});
		} if (editType == 'edit') {
			zlContext.post(layui.cache['contentPath'] + '/manager/coretables/modify', frm.field, function (result) {
				if (result[statusName] == OK) {
					treeAction.refreshNode(node, frm.field);
					layer.close(fromlayerIndex);
					zlContext.successMsg('保存成功');
					return true;
				}
				else {
					zlContext.errorMsg(result[msgName]);
				}
			});
		}
		return false;
	});
	// 新增节点
	$('#btnTreeNew').on('click', function () {
		treeAction.addNode();
	});
	// 编辑节点
	$('#btnTreeEdit').on('click', function () {
		treeAction.editNode();
	});
	// 删除节点
	$('#btnTreeDelete').on('click', function () {
		treeAction.deleteNode();
	});
	// 更新
	$('#btnTreeRefresh').on('click', function () {
		treeAction.loadTree();
	});

	//加载树
	treeAction.loadTree();
	var dbTypes = {};
	//同步获取数据库类型
	zlContext.asyncGet(
		layui.cache['contentPath'] + '/manager/coretablescolumn/queryfielddatatypeList?RWID=F29725BB1E024C4C8AA2988E4967E971&bFilterPK=0'
		, null
		, function (result) {
			if (result[statusName] == OK) {
				$(result[dataName]).each(function (index, obj) {
					dbTypes[obj.CODE] = obj.VALUE;
				});
			}
			else {
				zlContext.errorMsg(result[msgName]);
				return;
			}
		},false);
	//渲染字段列表
	table.render({
		elem: '#tbField'
		, height: fullheight
		, response: zlConfig.global.gridResponse
		, limit: 999
		, toolbar: "#toolbarField"
		, defaultToolbar: []
		, cols: [[ //表头
			{ type: 'numbers', fixed: 'left', title: '#' }
			, { type: 'checkbox', fixed: 'left' }
			, {
				field: 'MXZD_SHIFCJ', title: '同步', width: 60, fixed: 'left', templet: function (d) {
					return '<input type="checkbox" name="MXZD_SHIFCJ" value="' + d.MXZD_SHIFCJ + '" disabled lay-skin="primary" ' + (d.MXZD_SHIFCJ ? "checked" : "") + '>'
				}
			}
			, { field: 'MXZD_MINGC', title: '名称', width: 100, sort: true }
			, { field: 'MXZD_BIANH', title: '编号', width: 150, sort: true }
			, { field: 'MXZD_YINGWM', title: '英文编号', width: 80, sort: true }
			, {
				field: 'MXZD_ZIDLX', title: '类型', width: 100, sort: true, templet: function (d) {
					return '<span>' + dbTypes[d.MXZD_ZIDLX] + '</span>'
				}
			}
			, { field: 'MXZD_ZIDCD', title: '长度', width: 60, sort: true }
			, { field: 'MXZD_MIAOS', title: '描述', width: 60, sort: true }
			, {
				field: 'MXZD_SHIFWY', title: '唯一', width: 60, templet: function (d) {
					return '<input type="checkbox" name="MXZD_SHIFWY" value="' + d.MXZD_SHIFWY + '" disabled lay-skin="primary" ' + (d.MXZD_SHIFWY ? "checked" : "") + '>'
				}
			}
			, {
				field: 'MXZD_YUNXWK', title: '为空', width: 60, templet: function (d) {
					return '<input type="checkbox" name="MXZD_YUNXWK" value="' + d.MXZD_YUNXWK + '" disabled lay-skin="primary" ' + (d.MXZD_YUNXWK ? "checked" : "") + '>'
				}
			}

			, { field: 'MXZD_XIAOSJD', title: '小数精度', width: 80, sort: true }
			, { field: 'SYS_SORT', title: '排序', width: 80, sort: true }
			, { fixed: 'right', width: 180, title: '操作', align: 'center', toolbar: '#barField' }
		]]
		, event:
		{
			onRowdbClick: function (field, row) {
				fieldGridAction.viewRow(row);
			}
		}
	});

	var fieldGridAction = {
		currentEditObj: undefined,
		fieldGridedit: function (tableid, row, type, readonly) {
			var readonly = readonly && readonly != 0 ? 'disabled' : '';
			var frm = [
				'<div class="site-block" lay-filter="divgridField"> <form id ="frmGridField" lay-filter="frmGridField" class="layui-form"  action="">'
				, '	<div class="layui-form-item layui-hide">'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="EDITTYPE" class="layui-input">'
				, '			<input type="text" name="RWID" class="layui-input">'
				, '			<input type="text" name="MXZD_TABLEID" class="layui-input">'
				, '			<input type="text" name="MXZD_SHIFCJ" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">名称</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" maxlength="30" name="MXZD_MINGC" ' + readonly + ' lay-verify="required|commentVerify" placeholder="请输入名称" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">编号</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" maxlength="30" name="MXZD_BIANH" ' + readonly + ' lay-verify="required|columnName" placeholder="请输入编号" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">字段类型</label>'
				, '		<div class="layui-input-block">'
				, '			<select name="MXZD_ZIDLX" lay-filter="MXZD_ZIDLX" ' + readonly + ' lay-verify="required" placeholder="请选择字段类型" default="2"  zlcomponent class="select-ext" settings="{placeholder:\'请选择字段类型\', titlefield: \'VALUE\', valuefield: \'CODE\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coretablescolumn/queryfielddatatypeList?RWID=F29725BB1E024C4C8AA2988E4967E971&bFilterPK=' + ( readonly == 'disabled' ? '0' : '1') + '\'}">'
				, '			</select>'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">英文名</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" maxlength="16" name="MXZD_YINGWM" ' + readonly + '   class="layui-input"> '
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<div class="layui-inline">'
				, '			<label class="layui-form-label">唯一</label>'
				, '			<div class="layui-input-block">'
				, '				<input type="checkbox"   name="MXZD_SHIFWY" valueformat="1|0" lay-skin="primary"' + readonly + '>'
				, '			</div>'
				, '		</div>'
				, '		<div class="layui-inline">'
				, '		<label class="layui-form-label">允许为空</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="checkbox" ' + (type == 'new' ? 'checked="true"' : '') + ' name="MXZD_YUNXWK" valueformat="1|0" lay-skin="primary"' + readonly + '>'
				, '		</div>'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label" id="label-MXZD_ZIDCD">字段长度</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="MXZD_ZIDCD" ' + readonly + ' lay-verify="verifyFieldLength" class="layui-input"> '
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">小数精度</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="MXZD_XIAOSJD" ' + readonly + ' lay-verify="verifyFieldPrecision"  class="layui-input"> '
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">描述</label>'
				, '		<div class="layui-input-block">'
				, '			<textarea placeholder="请输入描述" name="MXZD_MIAOS" maxlength="85" class="layui-textarea" ' + readonly + '></textarea>'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">排序</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="SYS_SORT" ' + readonly + ' lay-verify="number" class="layui-input" maxlength="7"> '
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item ' + (readonly == 'disabled' ? ' layui-hide"' : '"') + '">'
				, '		<div class="layui-input-block">'
				, '		  <button  id="btnSave" class="layui-btn" lay-submit lay-filter="frmGridField"  ' + readonly + '>保存</button>'
				, '		</div>'
				, '	</div>'
				, '</form></div>'
			];
			
			layer.open({
				type: 1,
				limit: 999,
				title: readonly == 'disabled' ? '查看' : (type == 'edit' ? '编辑' : '新增'),
				id: 'coreTableLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
					var $zdcd = $('#frmGridField input[name=MXZD_ZIDCD]'),
						$xsjd = $('#frmGridField input[name=MXZD_XIAOSJD]');
					if (readonly != 'disabled') {
						form.on('select(MXZD_ZIDLX)', function (data) {
							if(data.value == 'STRING(X)'){
								$zdcd.removeAttr('disabled');
								$zdcd.attr("lay-verify","required|verifyFieldLength");
							}else{
								$zdcd.attr('disabled', 'true');
								$zdcd.attr("lay-verify","");
							}
							if(data.value == 'DATETIME'){
								$zdcd.removeAttr('disabled');
								$('#label-MXZD_ZIDCD').html('毫秒长度')
							}else{
								$('#label-MXZD_ZIDCD').html('字段长度')
							}
							if(data.value == 'FLOAT(X)'){
								$xsjd.removeAttr('disabled');
								$xsjd.attr("lay-verify","required|verifyFieldPrecision");
							}else{
								$xsjd.attr("lay-verify","");
								$xsjd.attr('disabled', 'true');
							}
							var str = $('#frmGridField select[name=MXZD_ZIDLX]').find('option:selected').text();
							var reg = /\((\d+)\)/;
							if (reg.test(str)) { //如果匹配上直接获取括号里的内容
								//data.value != '10' ? $zdcd.val(RegExp.$1) : $zdcd.val(RegExp.$1);
								var endIndex = data.value.indexOf("(");
								var zdlxName = data.value.substr(0,endIndex);
								if (zdlxName == 'FLOAT') { //小数
									$zdcd.val('');
									$xsjd.val(RegExp.$1)
								} else if (zdlxName == 'STRING') {
									$zdcd.val(RegExp.$1);
									$xsjd.val('');
								} else {
									$zdcd.val('');
									$xsjd.val('');
								}
							} else if (data.value == 'PK'){
								$zdcd.val('32');
								$xsjd.val('');
							}else{
								$zdcd.val('');
								$xsjd.val('');
							}
							form.render(null,'frmGridField');
						});
					} else {
						$('[placeholder]').attr('placeholder','')
					}
					if (type == 'edit') {
						zlContext.autoFill($('#frmGridField'), row);
						$('#frmGridField input[name=EDITTYPE]').val('edit');
						if (readonly != 'disabled') {
							var $zdlx = $("#frmGridField select[name=MXZD_ZIDLX]");
							if($zdlx.val() == 'STRING(X)'){
								$zdcd.attr("lay-verify","required|verifyFieldLength");
								$zdcd.removeAttr('disabled');
							}else{
								$zdcd.attr("lay-verify","");
								$zdcd.attr('disabled', 'true');
							}

							if($zdlx.val() == 'FLOAT(X)'){
								$xsjd.removeAttr('disabled');
								$xsjd.attr("lay-verify","required|verifyFieldPrecision");
							}else{
								$xsjd.attr("lay-verify","");
								$xsjd.attr('disabled', 'true');
							}
							form.render(null,'frmGridField');
						}
					}
					else {
						/**设置隐藏属性*/
						$('#frmGridField input[name=EDITTYPE]').val('new');
						$('#frmGridField input[name=MXZD_SHIFCJ]').val('0');
						$('#frmGridField input[name=MXZD_TABLEID]').val(tableid);
						$('#frmGridField input[name=MXZD_SHIFWY]').val('0');
						$('#frmGridField select[name=MXZD_ZIDLX]').val('STRING(100)');

						//由于layui是主动刷新需要重新刷新才能显示出状态
						form.render();
						$('#frmGridField input[name=MXZD_MINGC]').change(function () {
							var v = $('#frmGridField input[name=MXZD_MINGC]').val();
							var h = $('#frmTable input[name=MX_BIANH]').val();
							/**设置字段名 */
							var v1 = zlPinYin.C(v);
							$('#frmGridField input[name=MXZD_BIANH]').val(v1);
							if (v.endWith('日期') || v.endWith('日')) {
								$('#frmGridField select[name=MXZD_ZIDLX]').val('DATE');
							}
							if (v.endWith('时间')) {
								$('#frmGridField select[name=MXZD_ZIDLX]').val('DATETIME');
							}
							if (v.endWith('价值') || v.endWith('单价') || v.endWith('数量') || v.endWith('数')) {
                                $('#frmGridField select[name=MXZD_ZIDLX]').val('FLOAT(2)');
                                $zdcd.attr('disabled', 'true');
                                $xsjd.attr("lay-verify","");
								$xsjd.attr('disabled', 'true');
							}
							form.render();
						});
					}
					fromlayerIndex = index;

				},
				cancel: function (index, layero) {
					if (type == 'edit' && readonly != 'disabled') {
						zlContext.isFormDataChange('frmGridField', fieldGridAction.currentEditObj.data, fieldGridAction, index)
						return false;
					}
				}
			});
		},
		//判断是否已经拥有主键了
		hasPrimaryKey: function () {
			var data = table.cache.tbField,
				ret = false;
			if (data) {
				$(data).each(function (index, row) {
					if (data['MXZD_ZIDLX'] == 'PK') {
						ret = true;
						return ret;
					}
				});
			}
			return ret;
		},
		viewRow: function (row) {
			fieldGridAction.fieldGridedit(null, row, 'edit', true);
		},
		newRow: function () {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length == 0) {
				zlContext.warnMsg('请选择模型节点');
				return;
			}
			if (nodes[0]['MX_BIAOLX'] == 2) {
				zlContext.warnMsg('模型类型是目录无法新增字段');
				return;
			}
			fieldGridAction.fieldGridedit(nodes[0]['RWID'], null, 'new');
		},
		editRow: function (row) {
			if (row['MXZD_BIANH'].indexOf('SYS_') == 0) {
				zlContext.warnMsg('无法修改系统字段');
				return;
			}
			if(row['MXZD_BIANH'] == "RWID"){
				zlContext.warnMsg('无法修改主键字段');
				return;
			}
			fieldGridAction.fieldGridedit(null, row, 'edit');
		},
		deleteRows: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要删除的字段');
				return;
			}
			var hasSysField = false;
			$(rows).each(function (index, obj) {
				if (obj['MXZD_BIANH'].indexOf('SYS_') == 0 || obj['MXZD_BIANH'] == "RWID") {
					zlContext.warnMsg('选择的字段中包含主键或系统字段，不可删除：' + obj['MXZD_BIANH']);
					hasSysField = true;
					return false;
				}
			});
			if (hasSysField) return;
			zlContext.confirm('询问', '是否要删除选择的字段?', function (index) {
				var ids = "";
				for (var i = 0; i < rows.length; i++) {
					ids += rows[i]['RWID'] + ","
				}
				ids = ids.substr(0, ids.length - 1);
				//提交删除
				zlContext.deletePost(layui.cache['contentPath'] + '/manager/coretablescolumn/remove', { id: ids }, function (result) {
					if (result[statusName] == OK) {
						if (rows[0].del) {
							fieldGridAction.currentEditObj.del();
						} else {
							fieldGridAction.refreshGrid('del', null);
						}
						zlContext.successMsg('删除成功');
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		updateFieldToDB: function(){
			//同步表结构
			if (treeAction.isRootNode() || treeAction.isCalNode()) {
				zlContext.warnMsg('无法更新根节点或目录类型的模型');
				return;
			}
			zlContext.post(layui.cache['contentPath'] + '/manager/coretables/modifytodb', { tbid: $('#frmTable input[name=RWID]').val() }, function (result) {
				if (result[statusName] == OK) {
					treeAction.raiseResDataEvent();
					zlContext.successMsg('成功同步表结构');
				}
				else {
					zlContext.errorMsg(result[msgName]);
				}
			});
		},
		exportField: function(){
			//导出表结构
            var nodes = treeObj.getSelectedNodes();
            if(nodes.length <= 0){
                zlContext.warnMsg('请选择需要导出的表模型！');
                return;
            }
            var frmExportField = [
                  '<div class="layui-form-item" style="margin-bottom: 0;">'
                , ' <div id="dataFilterTipInfo" class="layui-form-mid layui-word-aux" style="padding: 9px 10px !important;">请编辑where关键字之后的过滤条件</div>'
                , '</div>'
                , '<div class="layui-form-item layui-form-text" id="layer-item-title" style="margin-right: 10px;">'
                , '	<label class="layui-form-label" style="width:90px;display: block;padding-left: 10px;padding-right: 10px;">数据过滤条件:</label>'
                , '	<div id="ace-editor-contianer" class="layui-input-block" style="margin-left: 110px;">'
                , '	</div>'
                , '</div>'
            ];
            layer.open({
                type: 1
                , id: 'exportFieldLayer'
                , title: "编辑数据过滤条件"
                , area: ["600px", "400px"]
                , content: frmExportField.join('')
                , btn: ['确定', '取消']
                , success: function () {
                    var moduleCatalog = 2;
                    if(nodes.length == 1 && moduleCatalog != nodes[0].MX_BIAOLX){
                        $('#ace-editor-contianer').append('<div id="dataFilterCondition" style="min-height: 245px; overflow-y: auto;"></div>');
                        ace.require("ace/ext/language_tools");
                        var aceEditor = ace.edit("dataFilterCondition");
                        aceEditor.setOptions({
                            enableBasicAutocompletion: true,
                            enableSnippets: true,
                            enableLiveAutocompletion: true,//只能补全
                        });
                        aceEditor.setTheme("ace/theme/monokai");//monokai模式是自动显示补全提示
                        aceEditor.getSession().setMode("ace/mode/sql");//语言
                        aceEditor.getSession().setTabSize(4);
                        aceEditor.setFontSize(14);
                    }else{
                        $('#dataFilterTipInfo').text('数据过滤条件只支持单个表模型；多表模型情况将不进行数据过滤。');
                        $('#ace-editor-contianer').append('<textarea id="dataFilterCondition" disabled style="height: 245px;" class="layui-textarea"></textarea>');
                    }
                }
                , yes: function (index, layero) {
                    if (nodes.length > 0) {
                        var param = []
                        //获取数据过滤条件
                        var dataFilterCnd = "";
                        if(nodes.length == 1){
                            var aceEditor = ace.edit("dataFilterCondition");
                            dataFilterCnd = $.trim(aceEditor.getValue());
                        }
                        
                        for (i = 0; i < nodes.length; i++) {
                            param.push({
                                RWID: nodes[i]["RWID"],
                                dataFilterCnd: dataFilterCnd
                            });
                        }
                        loadingLayer = layer.msg('下载中，请稍候...', { icon: 16, time: false, shade: 0.1 });
                        var _downloadid = new Date().getTime();
                        var url = layui.cache['contentPath'] + '/manager/coretables/exportmodel';
                        var downloadform = document.getElementById('downloadform');
                        var $tbids = $('<input type="hidden" name="tbids" />').val(JSON.stringify(param));
                        var $_downloadid = $('<input type="hidden" name="_downloadid" />').val(_downloadid);
                        $(downloadform).empty().append($tbids).append($_downloadid);
                        downloadform.action = url;
                        downloadform.method = 'post';
                        downloadform.submit();
                        var iframe = document.getElementById('ifdownload');
                        iframe.onload = iframe.onreadystatechange = function iframeload() {
                            if(intervalId){
                                clearInterval(intervalId);
                            }
                            layer.close(loadingLayer);
                            if (!iframe.readyState || iframe.readyState == "complete") {
                                var iframeText = document.getElementById('ifdownload').contentWindow.document;
                                iframeText = $(iframeText).text();
                                if(iframeText){
                                    var obj = JSON.parse(iframeText);
                                    if(obj && obj[statusName] == OK){
                                        layer.close(index);
                                    }else{
                                        zlContext.errorMsg(obj.msg);
                                    }
                                }
                                
                            }
                        };
                        intervalId = setInterval(function(){
                            var cookieName = '_downloadid' + _downloadid;
                            var cookieValue = zlContext.getCookieValue(cookieName);
                            if(cookieValue && cookieValue == _downloadid){
                                layer.close(index);
                                layer.close(loadingLayer);
                                if(intervalId){
                                    clearInterval(intervalId);
                                    intervalId = undefined;
                                }
                            }
                        }, 500);
                    }
                },
                btn2: function(index, layero){
                    layer.close(index);
                }, cancel: function(index, layero){
                    layer.close(index);
                }
            });
		},
		sumbit: function (fields) {
			//将字段编号转成大写
            fields['MXZD_BIANH'] = fields['MXZD_BIANH'].toUpperCase();
            if(fields['MXZD_BIANH'].indexOf('SYS_') == 0 || fields['MXZD_BIANH'] == 'RWID'){
                zlContext.warnMsg('无法新增或修改系统字段');
				return false;
            }
			if (!fields['SYS_SORT']) {
				fields['SYS_SORT'] = 0;
			}
			var editType = $('#frmGridField input[name=EDITTYPE]').val();
			if (editType == 'new') {
				zlContext.put(layui.cache['contentPath'] + '/manager/coretablescolumn/add', fields, function (result) {
					if (result[statusName] == OK) {
						fieldGridAction.refreshGrid(editType, result[dataName]);
						layer.close(fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			} if (editType == 'edit') {
				// zlContext.post(layui.cache['contentPath'] + '/manager/coretablescolumn/modify', fields, function (result) {
				// 	if (result[statusName] == OK) {
				// 		fieldGridAction.refreshGrid(editType, fields);
				// 		layer.close(fromlayerIndex);
				// 		zlContext.successMsg('保存成功');
				// 		return true;
				// 	}
				// 	else {
				// 		zlContext.errorMsg(result[msgName]);
				// 	}
                // });
                fieldGridAction.editSubmit(fields);
			}
			return false;
        },
        editSubmit: function(fields){
            var param = { 
                'RWID': fields['RWID'],
                'MXZD_TABLEID': fields['MXZD_TABLEID']
            }
            zlContext.get(layui.cache['contentPath'] + '/manager/coretables/querytabledetail', param, function (result) {
                if (result[statusName] = OK && result[dataName]) {
                    var obj = result[dataName];
                    var bCond = (obj['bTable'] != '1' || obj['bColumn'] != '1' || obj['recordCount'] <= 0);
                    var row = fieldGridAction.currentEditObj.data;
                    bCond = (bCond || (row['MXZD_MINGC'] == fields['MXZD_MINGC'] && row['MXZD_BIANH'] == fields['MXZD_BIANH'] 
                        &&row['MXZD_SHIFWY'] == fields['MXZD_SHIFWY'] && row['MXZD_YUNXWK'] == fields['MXZD_YUNXWK'] 
                        && row['MXZD_ZIDLX'] == fields['MXZD_ZIDLX'] && row['MXZD_ZIDCD'] == fields['MXZD_ZIDCD'] && row['MXZD_XIAOSJD'] == fields['MXZD_XIAOSJD']));
                    if(bCond){
                        zlContext.post(layui.cache['contentPath'] + '/manager/coretablescolumn/modify', fields, function (ret) {
                            if (ret[statusName] == OK) {
                                fieldGridAction.refreshGrid('edit', fields);
                                layer.close(fromlayerIndex);
                                zlContext.successMsg('修改成功');
                                return true;
                            }
                            else {
                                zlContext.errorMsg(ret[msgName]);
                            }
                        }, false);
                    }else{
                        zlContext.confirm('询问', '表中存在数据，修改字段类型、长度、精度、唯一性、是否为空等，可能会导致数据丢失和修改失败，并且影响系统正常运行，是否确认修改?', function (index) {
                            var layerIndex = layer.msg('数据提交中，请稍候...', { icon: 16, time: false, shade: 0.1 });
                            zlContext.post(layui.cache['contentPath'] + '/manager/coretablescolumn/modify', fields, function (ret) {
                                layer.close(layerIndex);
                                if (ret[statusName] == OK) {
                                    fieldGridAction.refreshGrid('edit', fields);
                                    layer.close(fromlayerIndex);
                                    zlContext.successMsg('修改成功');
                                    return true;
                                }
                                else {
                                    zlContext.errorMsg(ret[msgName]);
                                }
                            }, false);
                            layer.close(index);
                        });
                    }
                } else {
                    layer.close(layerIndex);
                    zlContext.errorMsg(result[msgName]);
                }
            });
        },
		refreshGrid: function (type, row) {
			/**刷新行 */
			if (type == 'edit' && fieldGridAction.currentEditObj) {
				fieldGridAction.currentEditObj.update(row);
				table.reload('tbField');
			} else if (type == 'new') {
				table.reload('tbField');
			} else if (type == 'del') {
				if (fieldGridAction.currentEditObj) {
					table.reload('tbField');
					return;
				}
				table.deleteCheckRows('tbField');
			}
			form.render();
		}
	}

	//头工具栏事件
	table.on('toolbar(tbField)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
		switch(obj.event){
			case 'addField':
				fieldGridAction.newRow();
				break;
			case 'deleteField':
				var rows = checkStatus.data;
				fieldGridAction.deleteRows(rows);
				break;
			case 'updateFieldToDB':
				fieldGridAction.updateFieldToDB();
				break;
			case 'exportField':
				fieldGridAction.exportField();
				return false;
        };
	});
	//监听行工具事件
	table.on('tool(tbField)', function (obj) {
		var row = obj.data; //获得当前行数据
		var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
		var tr = obj.tr; //获得当前行 tr 的DOM对象
		if (layEvent === 'detail') { //查看
			fieldGridAction.viewRow(row)
		} else if (layEvent === 'del') { //删除
			fieldGridAction.currentEditObj = obj;
			fieldGridAction.deleteRows([row]);
		} else if (layEvent === 'edit') { //编辑
			fieldGridAction.currentEditObj = obj;
			fieldGridAction.editRow(row);
		}
	});
	//提交
	form.on('submit(frmGridField)', function (frm) {
		if ($(frm.elem).hasClass('getField')) {
			fieldGridAction.newFields = frm.field
			return false;
		}
		return fieldGridAction.sumbit(frm.field);
	});
	//校验字段长度和精度
	form.verify({
		verifyFieldLength: function(value, item){
			if(value){
				if(!/^\d+$/.test(value)){
					return '只能填写大于0且小于等于4000的正整数'
				}else{
					if(value*1 <= 0 || value*1 > 4000){
						return '只能填写大于0且小于等于4000的正整数'
					}
				}
			}
		},
		verifyFieldPrecision: function(value, item){
			if(value){
				if(!/^\d+$/.test(value)){
					return '只能填写大于0且小于等于10的正整数'
				}else{
					if(value*1 <= 0 || value*1 > 10){
						return '只能填写大于0且小于等于10的正整数'
					}
				}
			}
		}
	});
	// //渲染约束列表
	// table.render({
	// 	elem: '#tbLink'
	// 	, height: fullheight
	// 	, response: zlConfig.global.gridResponse
	// 	, cols: [[ //表头
	// 		{ type: 'numbers', fixed: 'left', title: '#' }
	// 		, { fixed: 'right', width: 150, align: 'center', toolbar: '#barLink' }
	// 		, { type: 'checkbox', fixed: 'left' }
	// 		, { field: 'MXYS_BIANH', title: '约束编号', width: 80, fixed: 'left' }
	// 		, { field: 'MXYS_XUYGLZD', title: '需关联字段', width: 80, fixed: 'left' }
	// 		, { field: 'MXYS_GUANLB', title: '关联的表', width: 80 }
	// 		, { field: 'MXYS_GUANLBZD', title: '关联表字段', width: 80 }
	// 		, { field: 'MXYS_GUANLBLX', title: '关联类型', width: 80 }
	// 		, {
	// 			title: '操作', width: 160, fixed: 'right', align: 'center', buttons: [
	// 				{ text: '编辑', clz: 'layui-btn layui-btn-xs', event: 'edit' }
	// 				, { text: '删除', clz: 'layui-btn layui-btn-danger layui-btn-xs', event: 'del' }
	// 			]
	// 		}
	// 	]]
	// });
	//渲染索引列表
	table.render({
		elem: '#tbIndex'
		, height: fullheight
		, response: zlConfig.global.gridResponse
		, limit: 1000
		, toolbar: "#toolbarIndex"
		, defaultToolbar: []
		, cols: [[ //表头
			{ type: 'numbers', fixed: 'left', title: '#' }
			, { type: 'checkbox', fixed: 'left' }
			, {
				field: 'MXSY_SHIFWY', fixed: 'left', title: '唯一', width: 100, templet: function (d) {
					return '<input type="checkbox" name="MXSY_SHIFWY" value="' + d.MXSY_SHIFWY + '" disabled lay-skin="primary" ' + (d.MXSY_SHIFWY ? "checked" : "") + '>'
				}
			}
			, { field: 'MXSY_BIANH', title: '索引编号', width: 100, fixed: 'left' }
			, { field: 'MXSY_ZIDLB', title: '字段列表', width: 380, fixed: 'left' }
			, { type: '', fixed: 'right', width: 180, title: '操作', align: 'center', toolbar: '#barIndex' }
		]]
	});

	var indexGridAction = {
		currentEditObj: undefined,
		Gridedit: function (tableid, row, type, readonly) {
			var readonly = readonly && readonly != 0 ? 'disabled' : '';
			var frm = [
				'<div class="site-block"> <form id ="frmGridIndex" class="layui-form"  action="">'
				, '	<div class="layui-form-item layui-hide">'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="EDITTYPE" class="layui-input">'
				, '			<input type="text" name="RWID" class="layui-input">'
				, '			<input type="text" name="MXSY_TABLEID" class="layui-input">'
				, '			<input type="text" name="MXSY_SHIFCJ" class="layui-input">'
				, '			<input type="text" name="MXSY_BIANH" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '			<label class="layui-form-label">唯一索引</label>'
				, '			<div class="layui-input-block">'
				, '				<input type="checkbox"  name="MXSY_SHIFWY" lay-skin="switch" lay-text="是|否" valueformat="1|0"' + readonly + '>'
				, '			</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '			<label class="layui-form-label">字段列表</label>'
				, '			<div class="layui-input-block">'
				, '		  		<div name="MXSY_ZIDLB" lay-verify="required|indexlbverify" zlcomponent=""  class="layui-form-select select-multiple" settings="{edittype:\'' + readonly + '\',placeholder:\'请选择字段列表\', titlefield: \'VALUE\', valuefield: \'KEY\',dataurl:\'' + layui.cache['contentPath'] + '/manager/coretablescolumn/findcolumnkeyvaluesfilterpklist?MXZD_TABLEID=' + tableid + '\'}">'
				, '		  		</div>'
				, '			</div>'
				, '	</div>'
				, '	<div class="layui-form-item' + (readonly == 'disabled' ? ' layui-hide"' : '"') + '>'
				, '		<div class="layui-input-block">'
				, '		  <button class="layui-btn" lay-submit lay-filter="frmGridIndex">保存</button>'
				, '		</div>'
				, '	</div>'
				, '</form></div>'
			];
			layer.open({
				type: 1,
				title: readonly == 'disabled' ? '查看' : (type == 'edit' ? '编辑' : '新增'),
				id: 'coreTableGridLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
					if (type == 'edit') {
						zlContext.autoFill($('#frmGridIndex'), row);
						$('#frmGridIndex input[name=EDITTYPE]').val('edit');
					}
					else {
						form.render();
						/**设置隐藏属性*/
						$('#frmGridIndex input[name=EDITTYPE]').val('new');
						$('#frmGridIndex input[name=MXSY_SHIFCJ]').val('0');
						$('#frmGridIndex input[name=MXSY_TABLEID]').val(tableid);
					}
					fromlayerIndex = index;
				},
				cancel: function (index, layero) {
					if (type == 'edit' && readonly != 'disabled') {
						zlContext.isFormDataChange('frmGridIndex', indexGridAction.currentEditObj.data, indexGridAction, index)
						return false;
					}
				}
			});
		},
		viewRow: function (row) {
			indexGridAction.Gridedit(row['MXSY_TABLEID'], row, 'edit', true);
		},
		newRow: function () {
			var nodes = treeObj.getSelectedNodes();
			if (nodes.length == 0) {
				zlContext.warnMsg('请选择模型节点');
				return;
			}
			if (nodes[0]['MX_BIAOLX'] == 2) {
				zlContext.warnMsg('模型类型是[目录]无法新增字段');
				return;
			}
			indexGridAction.Gridedit(nodes[0]['RWID'], null, 'new');
		},
		editRow: function (row) {
			indexGridAction.Gridedit(row['MXSY_TABLEID'], row, 'edit');
		},
		deleteRows: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要删除的索引');
				return;
			}
			var hasSysField = false;
			if (hasSysField) return;
			zlContext.confirm('询问', '是否要删除选择的索引?', function (index) {
				var ids = "";
				for (var i = 0; i < rows.length; i++) {
					ids += rows[i]['RWID'] + ","
				}
				ids = ids.substr(0, ids.length - 1);
				//提交删除
				zlContext.deletePost(layui.cache['contentPath'] + '/manager/coretablesindex/remove', { id: ids }, function (result) {
					if (result[statusName] == OK) {
						if (rows[0].del)
							indexGridAction.currentEditObj.del();
						else
							indexGridAction.refreshGrid('del', null);
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
				layer.close(index);
			});
		},
		sumbit: function (indexs) {
			if(indexs["MXSY_ZIDLB"] && indexs["MXSY_ZIDLB"].length > 512){
				zlContext.warnMsg('选择的字段列表过多，请减少');
				return false;
			}
			var editType = $('#frmGridIndex input[name=EDITTYPE]').val();
			if (editType == 'new') {
				zlContext.put(layui.cache['contentPath'] + '/manager/coretablesindex/add', indexs, function (result) {
					if (result[statusName] == OK) {
						indexGridAction.refreshGrid(editType, result[dataName]);
						layer.close(fromlayerIndex);
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			} if (editType == 'edit') {
				zlContext.post(layui.cache['contentPath'] + '/manager/coretablesindex/modify', indexs, function (result) {
					if (result[statusName] == OK) {
						indexGridAction.refreshGrid(editType, indexs);
						layer.close(fromlayerIndex);
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			return false;
		},
		refreshGrid: function (type, row) {
			/**刷新行 */
			if (type == 'edit' && indexGridAction.currentEditObj) {
				indexGridAction.currentEditObj.update(row);
			} else if (type == 'new') {
				table.reload('tbIndex');
			} else if (type == 'del') {
				if (indexGridAction.currentEditObj) {
					table.reload('tbIndex');
					return;
				}
				table.deleteCheckRows('tbIndex');
			}
			form.render();
		}
	}
	//头工具栏事件
	table.on('toolbar(tbIndex)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
		switch(obj.event){
			case 'addIndex':
				indexGridAction.newRow();
				break;
			case 'deleteIndex':
				var rows = checkStatus.data;
				indexGridAction.deleteRows(rows);
				break;
		};
	});
	//监听行工具事件
	table.on('tool(tbIndex)', function (obj) {
		var row = obj.data; //获得当前行数据
		var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
		var tr = obj.tr; //获得当前行 tr 的DOM对象
		if (layEvent === 'detail') { //查看
			indexGridAction.viewRow(row)
		} else if (layEvent === 'del') { //删除
			indexGridAction.currentEditObj = obj;
			indexGridAction.deleteRows([row]);
		} else if (layEvent === 'edit') { //编辑
			indexGridAction.currentEditObj = obj;
			indexGridAction.editRow(row);
		}
	});
	//版本校验
	form.verify({
		indexlbverify: function (value, item) {
			if (value) {
				if (value.length >= 512) {
					$(item).focus();
					return '请选择字段列表长度不能超过512字符';
				}
			} else {
				return '请选择字段列表';
			}
		}
	});
	//提交
	form.on('submit(frmGridIndex)', function (frm) {
		if ($(frm.elem).hasClass('getField')) {
            indexGridAction.newFields = frm.field
            return false;
        }
		return indexGridAction.sumbit(frm.field);
	});

	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
		zlContext.get(
			layui.cache['contentPath'] + '/manager/coretables/query'
			, { RWID: param }
			, function (result) {
				if (result[statusName] == OK) {
					zlContext.autoFill($('#frmTable'), result[dataName][0], null);
				}
				else {
					zlContext.errorMsg(result[msgName]);
					return;
				}
				var loadGridData = function (tableId, url, param) {
					table.reload(tableId, {
						url: url
						, where: param
						, parseData: function (res) {
							if (tableId == 'tbField') {
								exportData['tbField'] = res[zlConfig.global.result.dataName]
							}
						}
					});
				}
				//刷新
				loadGridData('tbField', layui.cache['contentPath'] + '/manager/coretablescolumn/query', { MXZD_TABLEID: param });
				//loadGridData('tbLink', layui.cache['contentPath'] + '/manager/coretablescolumn/query', { MXYS_TABLEID: param });
				loadGridData('tbIndex', layui.cache['contentPath'] + '/manager/coretablesindex/query', { MXSY_TABLEID: param });
			},false);
	});

	// 点击任意位置隐藏右键菜单
	$(window).on('click', function () {
		$('#rightButtonMenu').addClass('layui-hide').removeClass('layui-show')
	})
	
	$(window).on('resize', function () {
		zlContext.setMaxHeihgt(0);
	}).resize();
});